# 自定义函数计算网格距离
def haversine_fun(last_stay_grid_id, grid_id):
    if last_stay_grid_id is None:
        return 0.0

    import math
    lon1 = float(last_stay_grid_id[:7]) / 10000
    lat1 = float(last_stay_grid_id[7:]) / 1000000

    lon2 = float(grid_id[:7]) / 10000
    lat2 = float(grid_id[7:]) / 1000000

    # 将经纬度从度转换为弧度
    lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])

    # Haversine公式
    dlat = lat2 - lat1
    dlon = lon2 - lon1
    a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
    c = 2 * math.asin(math.sqrt(a))

    # 地球半径(千米)
    r = 6371.393
    return round(c * r, 3)